const router = require('express').Router()
const pool = require('../db/pool.js')

//引入支付宝配置文件
const alipaySdk = require('../util/alipayuntils.js')
const AlipayFormData = require('alipay-sdk/lib/form').default
const axios = require('axios')

//更新支付状态
router.get('/payment', async function (req, res, next) {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return
  }

  let sql = `select * from indent where consumer_id = ${req.user.id}`
  let result2 = await pool.query(sql)
  let indents = result2[0]

  for (const indent of indents) {
    //订单号
    let order_id = indent.order_id;
    //支付宝配置
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    //支付时信息
    formData.addField('bizContent', {
      outTradeNo: order_id
    });
    //返回promise
    const result = alipaySdk.exec(
      'alipay.trade.query',
      {},
      { formData: formData },
    );
    //后端请求支付宝
    result.then(resData => {
      axios({
        method: 'GET',
        url: resData
      }).then(async data => {
        let responseCode = data.data.alipay_trade_query_response
        if (responseCode.code == '10000') {
          if (responseCode.trade_status == 'TRADE_FINISHED' || responseCode.trade_status == 'TRADE_SUCCESS') {
            let sql = `update indent set status = 3 where order_id = ${order_id}`
            let result = await pool.query(sql)
            
          }
        }
      })
    })
  }

  res.status(200).json({
    msg: '更新成功'
  })
})

router.post('/indent/add', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return
  }

  function setTimeDateFmt(s) {
    return s < 10 ? '0' + s : s
  }
  function randomNumber() {
    const now = new Date();
    let month = now.getMonth() + 1;
    let day = now.getDate();
    let hour = now.getHours();
    let minutes = now.getMinutes();
    let seconds = now.getSeconds();
    month = setTimeDateFmt(month);
    day = setTimeDateFmt(day);
    hour = setTimeDateFmt(hour);
    minutes = setTimeDateFmt(minutes);
    seconds = setTimeDateFmt(seconds);
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    return orderCode;
  }

  try {
    let { delivery_address_id, price, items } = req.body
    let consumer_id = req.user.id
    let order_id = randomNumber()
    console.log(order_id)
    let sql = `insert into indent (consumer_id, delivery_address_id, price, status, order_id) values (${consumer_id}, ${delivery_address_id}, ${price}, 1, ${order_id})`
    let result = await pool.query(sql)
    let insertId = result[0].insertId

    for (const item of items) {
      sql = `insert into indent_item (indent_id, goods_id, num) values (${insertId}, ${item.goods_id}, ${item.num})`
      result = await pool.query(sql)
    }

    //开始对接支付宝API
    const formData = new AlipayFormData();
    // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
    formData.setMethod('get');
    //支付时信息
    formData.addField('bizContent', {
      outTradeNo: order_id,//订单号
      productCode: 'FAST_INSTANT_TRADE_PAY',//写死的
      totalAmount: price,//价格
      subject: '茶叶',//商品名称
    });
    //支付成功或者失败跳转的链接
    formData.addField('returnUrl', 'http://localhost:8080/pay');
    //返回promise
    const result2 = alipaySdk.exec(
      'alipay.trade.wap.pay',
      {},
      { formData: formData },
    );
    //对接支付宝成功，支付宝方返回的数据
    result2.then(resp => {
      res.status(200).json(resp)
    })

  } catch (error) {
    console.log(error)
    res.status(500).json({
      msg: '生成订单失败'
    })
  }
})

router.delete('/indent/del', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return
  }

  try {
    let id = req.query.id
    let sql = `delete from indent_item where indent_id = ${id}`
    let result = await pool.query(sql)

    sql = `delete from indent where id = ${id}`
    result = await pool.query(sql)

    res.status(200).json({
      msg: '删除成功'
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({
      msg: '删除失败'
    })
  }
})

router.put('/indent/status', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return
  }

  try {
    let { id, status } = req.body
    let sql = `update indent set status = ${status} where id = ${id}`
    let result = await pool.query(sql)

    res.status(200).json({
      msg: '更新成功'
    })
  } catch (error) {
    console.log(error)
    res.status(500).json({
      msg: '更新失败'
    })
  }
})

router.get('/indent', async (req, res) => {
  if (!req.user) {
    res.status(403).json({
      msg: '用户未登录'
    })
    return
  }

  try {
    let consumer_id = req.user.id
    let sql = `select * from indent where consumer_id = ${consumer_id}`
    let result = await pool.query(sql)
    let indents = result[0]

    for (const indent of indents) {
      sql = `select * from indent_item where indent_id = ${indent.id}`
      result = await pool.query(sql)
      let items = result[0]
      indent.items = items
      for (const item of items) {
        sql = `select * from goods where id = ${item.goods_id}`
        let ret = await pool.query(sql)
        let goods = ret[0][0]
        item.goods = goods
        delete item.goods_id
      }
    }

    res.status(200).json(indents)
  } catch (error) {
    console.log(error)
    res.status(500).json({
      msg: '查找失败'
    })
  }
})

module.exports = router